from google.appengine.ext import db
from session import _User
import random, string
import config

class _Printer(db.Model):
    user = db.ReferenceProperty(_User)
    printerid = db.StringProperty()
    eprint_enabled = db.BooleanProperty()
    publish_addr = db.EmailProperty()
    verify_sender_address = db.BooleanProperty()
    allowed_sender_addresses = db.StringListProperty()

    def AcceptSender(self, senderAddr):
        return (not self.verify_sender_address or senderAddr in self.allowed_sender_addresses)
    
    @classmethod
    def EnableEPrint(cls, printerid, user, addr=None):
    
        printer = cls.Get(printerid, user)
        if(not printer):
            printer = cls.Add(printerid=printerid, user=user, eprint_enabled=True, publish_addr=addr)
        else:
            printer.eprint_enabled = True
            if(addr):
                printer.publish_addr = addr
            printer.put()
        return printer
    
    
    @classmethod
    def DisableEPrint(cls, printerid, user):
        printer = cls.Get(printerid, user)
        if(printer):
            printer.eprint_enabled = False
            printer.put()
        return printer
        
    @classmethod
    def RenewPublishAddr(cls, printerid, user):
        printer = cls.Get(printerid, user)
        if(printer):
            printer.publish_addr = cls.GenerateEmail()
            printer.put()
        return printer

    @classmethod
    def Add(cls, printerid, user, eprint_enabled=False, publish_addr=None, verify_sender_address=False, allowed_sender_addresses=None):
        p = cls(printerid=printerid,
                eprint_enabled=eprint_enabled,
                user=user,
                publish_addr=publish_addr or cls.GenerateEmail(),
                verify_sender_address=verify_sender_address,
                allowed_sender_addresses=[user.email],
                )
        p.put()
        return p

    @classmethod
    def Get(cls, printerid, user):
        printers = cls.all().filter('printerid =', printerid).filter('user =', user).fetch(1)
        return printers and printers[0] or None

    @classmethod
    def FromPublishEmail(cls, email):
        printers = cls.all().filter('publish_addr =', email).fetch(1)
        return printers and printers[0] or None

    @classmethod
    def EmailExists(cls, email):
        return len(cls.all().filter('publish_addr =', email).fetch(1)) != 0
    
    @classmethod
    def GenerateEmail(cls):
        email = cls.RandomEmailAddr()
        while (cls.EmailExists(email)):
            email = cls.RandomEmailAddr()
        return email;
    
    @classmethod
    def RandomEmailAddr(cls):
        return config.email_addr(''.join((random.choice(string.ascii_lowercase + string.digits) for x in range(10))))

